package com.ningxun.pagent.web.controller.wechat;

import com.ningxun.pagent.bus.domain.wechatuser.BaseWechatUser;
import com.ningxun.pagent.bus.service.basewechatuser.IBaseWechatUserService;
import com.ningxun.pagent.common.config.PagentConfig;
import com.ningxun.pagent.common.core.controller.BaseController;
import com.ningxun.pagent.common.core.domain.AjaxResult;
import com.ningxun.pagent.common.utils.DateUtils;
import com.ningxun.pagent.common.utils.SecurityUtils;
import com.ningxun.pagent.common.utils.StringUtils;
import com.ningxun.pagent.common.utils.file.FileUploadUtils;
import com.ningxun.pagent.common.utils.file.FileUtils;
import com.ningxun.pagent.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/wechat/user")
public class WechatUser extends BaseController {

    @Autowired
    private IBaseWechatUserService baseWechatUserService;

    @Autowired
    private ServerConfig serverConfig;

    @GetMapping(value = "getdata")
    public AjaxResult getinfoByUserid(){
        BaseWechatUser baseWechatUser = baseWechatUserService.selectBaseWechatUserByUserId(SecurityUtils.getUserId());
        return success(baseWechatUser);
    }

    /**
     * 修改用户信息
     *
     */
    @PutMapping
    public AjaxResult edit(@RequestBody BaseWechatUser baseWechatUser)
    {
        baseWechatUser.setUserId(SecurityUtils.getUserId());
        return toAjax(baseWechatUserService.updateBaseWechatUser(baseWechatUser));
    }

    //修改头像
    @PostMapping("/avatar")
    public AjaxResult uploadAvatar(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = PagentConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = StringUtils.join(serverConfig.getUrl(), fileName);
            //传到数据库
            BaseWechatUser baseWechatUser = new BaseWechatUser();
            baseWechatUser.setUserId(SecurityUtils.getUserId());
            baseWechatUser.setAvatar(url);
            baseWechatUser.setUpdateTime(DateUtils.getNowDate());
            baseWechatUserService.updateBaseWechatAvatar(baseWechatUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}